package org.jfinanceobserver.utillities;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.jfinanceobserver.persistence.ConnFactory;
import org.jfinanceobserver.persistence.jpa.controller.QuotesActiveJpaController;
import org.jfinanceobserver.persistence.jpa.entities.QuotesActive;

/**
 * This is the active quotes
 *
 * $Author: r78v10a07@gmail.com $ $LastChangedDate: 2013-02-11 14:03:43 +0100
 * (Mon, 11 Feb 2013) $ $LastChangedRevision: 34 $
 *
 * @since Feb 10, 2013
 */
public class QuotesActives {

    private StringBuilder actives = null;
    private List<QuotesActive> acts = null;
    private static QuotesActives singleton;

    private QuotesActives() {
        actives = new StringBuilder();

    }

    /**
     * Return a QuotesActives
     *
     * @return a QuotesActives
     */
    public static synchronized QuotesActives getInstance() {
        if (singleton == null) {
            singleton = new QuotesActives();
            singleton.retrieveQuotesActive();
        }
        return singleton;
    }
    
    private String parseURL(String data){
        return data.replace("^", "%5E");
    }

    private void retrieveQuotesActive() {
        HashMap parm = new HashMap<>();
        parm.put("active", true);
        QuotesActiveJpaController aController = new QuotesActiveJpaController(ConnFactory.getInstance().getFactory());
        acts = aController.useNamedQuery("QuotesActive.findByActive", parm);
        if (!acts.isEmpty()) {
            Iterator it = acts.iterator();
            while (it.hasNext()) {
                actives.append(parseURL(((QuotesActive) it.next()).getSymbol()));
                if (it.hasNext()) {
                    actives.append(",");
                }
            }
        }
    }
    
    /**
     * Get the active quotes
     *
     * @return the active quotes
     */
    public List<QuotesActive> getActives() {
        return acts;
    }

    /**
     * Get the Yahoo URL symbols for active quotes
     *
     * @return a string with the Yahoo URL symbols for active quotes
     */
    public String getActivestoString() {
        return actives.toString();
    }

    /**
     * Get the QuotesActive entity from the Symbol
     *
     * @param symbol the quote symbol
     * @return the QuotesActive entity
     */
    public QuotesActive findId(String symbol) {
        for (QuotesActive a : acts) {
            if (a.getSymbol().equals(symbol)) {
                return a;
            }
        }
        return null;
    }
}
